package com.sinothk.server.support.annotation.callback;

import com.alibaba.fastjson.JSON;
import com.sinothk.server.support.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * API统一返回引入：重写返回体
 */
@Slf4j
@ControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {

    //标记名称
    public static final String RESPONSE_RESULT_ANN = "RESPONSE-RESULT-ANN";

    //是否请求包含了包装注解标记，没有就直接返回，不需要重写返回体
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
//        ServletRequestAttributes sra = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());
//        HttpServletRequest request = sra.getRequest();
//        //判断请求是否有包装标记
//        ResponseResult responseResultAnn = (ResponseResult) request.getAttribute(RESPONSE_RESULT_ANN);
//        return responseResultAnn != null;
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes != null ? servletRequestAttributes.getRequest() : null;
        // 判断请求是否有包装标记
        ResponseResult responseResultAnn = (ResponseResult) (request != null ? request.getAttribute(RESPONSE_RESULT_ANN) : null);

        return responseResultAnn != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
//        log.debug("进入返回体重写格式处理中。。。。。");
        // 正常数据
        if (body == null) {
            return Result.ok();
        } else if (body instanceof Result || body instanceof File || body instanceof ResponseEntity) {
            return body;
        } else if (body instanceof String) {
            // 重点：String类型时，必须这样返回，否则会报错：cannot be cast to java.lang.String
            return JSON.toJSONString(Result.ok(body));
        }
        return Result.ok(body);
    }
}

